﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using System.Security.Claims;

namespace AMS.Services.Authentication;

public class UserValidator : IResourceOwnerPasswordValidator
{
    private readonly DbContext _context;

    public UserValidator(DbContext context)
    {
        _context = context;
    }

    public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
        try
        {
            var user = await _context.Set<User>().Select(n => new { n.Id, n.Account, n.Password }).FirstOrDefaultAsync(n => n.Account == context.UserName);

            context.Result = user is not null && (App.Validate(user.Password, context.Password) || user.Password == context.Password)
                ? new GrantValidationResult(
                    user.Id.ToString(), OidcConstants.AuthenticationMethods.Password, new List<Claim>() { new Claim(JwtClaimTypes.Name, user.Account) })
                : new GrantValidationResult(
                    TokenRequestErrors.InvalidGrant, "Incorrect username or password.");
        }
        catch
        { }
    }
}